package code1;

import java.util.TreeMap;

/**
 * @author noob
 * @version 1.0
 * @date 2021/3/20 6:52
 */
public class Trie {



    private class Node{
        public boolean isWord;
        public TreeMap<Character,Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            next = new TreeMap<>();
        }

        public Node() {
            this(false);
        }
    }


    private Node root;
    private int size;

    public Trie() {
        this.root = new Node();
        this.size = 0;
    }

    //获得trie中存储单词的数量
    public int getSize(){
        return size;
    }

    //向trie中添加一个新的单词
    public void add(String word){
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if(cur.next.get(c)==null){
                cur.next.put(c,new Node());
            }
            cur= cur.next.get(c);
        }
        if(!cur.isWord){
            cur.isWord = true;
            size++;
        }
    }


    //查询单词word是否在Trie中
     public boolean contains(String word){
        Node cur = root;
         for (int i = 0; i < word.length(); i++) {
             char c = word.charAt(i);
             if(cur.next.get(c) ==null){
                 return false;
             }
             cur = cur.next.get(c);
         }
         return cur.isWord; //遍历完整个word,需要判断cur是不是一个完整的word;
     }




     //查询是在Trie中有单词以prefix为前缀
    public boolean isPrefix(String prefix){
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if(cur.next.get(c)==null){
                return false;
            }
            cur = cur.next.get(c);
        }
        return  true;
    }




}
